package com.biostime.springdraw.modules.sys.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.biostime.springdraw.common.config.Global;
import com.biostime.springdraw.common.persistence.TreeList;
import com.biostime.springdraw.common.utils.StringUtils;
import com.biostime.springdraw.common.web.BaseController;
import com.biostime.springdraw.modules.sys.entity.Menu;
import com.biostime.springdraw.modules.sys.service.MenuService;
import com.biostime.springdraw.modules.sys.utils.UserUtils;

@Controller
@RequestMapping(value="${adminPath}/sys/menu")
public class MenuController extends BaseController {
	
	@Autowired
	private MenuService menuService;
	
	private String contextPath;

	@ModelAttribute
	public Menu get(@RequestParam(required=false) String id) {
		Menu entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = menuService.get(id);
		}
		if (entity == null){
			entity = new Menu();
		}
		return entity;
	}
	
	@RequiresPermissions("sys:menu:view")
	@RequestMapping(value = {"list", ""})
	public String list(Menu menu, HttpServletRequest request, HttpServletResponse response, Model model) {
		//Page<Menu> page = menuService.findPage(new Page<Menu>(request, response), menu); 
		//model.addAttribute("page", page);
		List<Menu> list = menuService.findList(menu);
		TreeList<Menu> treeList = new TreeList<Menu>(list,null);
		
		model.addAttribute("list", treeList.toList());
		
		return "modules/sys/menuList";
	}

	@RequiresPermissions("sys:menu:view")
	@RequestMapping(value = "form")
	public String form(Menu menu, Model model) {
		List<Menu> parentMenus = menuService.getParentsTree();
		
		model.addAttribute("parentMenus",parentMenus);
		
		model.addAttribute("menu", menu);
		return "modules/sys/menuForm";
	}

	@RequiresPermissions(value={"sys:menu:edit","sys:menu:add"}, logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(Menu menu, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, menu)){
			return form(menu, model);
		}
		
		/**权限标识**/
		String[] permissions = request.getParameterValues("permission");
		if(permissions!=null && permissions.length>0){
			String permission = "";
			for(String p : permissions){
				permission += p+ ",";
			}
			
			menu.setPermission(StringUtils.substringBeforeLast(permission, ","));
		}
		
		menuService.save(menu);
		
		// 清除用户菜单缓存
		UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
		
		addMessage(redirectAttributes, "保存成功");
		return "redirect:"+Global.getAdminPath()+"/sys/menu/?repage";
	}
	
	@RequiresPermissions("sys:menu:edit")
	@RequestMapping(value = "delete")
	public String delete(@RequestParam(value="ids",required=false) String idsRequest, Menu menu, RedirectAttributes redirectAttributes) {
		//批量删除
		if(!StringUtils.isEmpty(idsRequest)){
			String[] ids = idsRequest.split(",");
			for(String id : ids){
				menuService.delete(new Menu(id));
			}
		}else{
			menuService.delete(menu);
		}
		
		// 清除用户菜单缓存
		UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
		
		addMessage(redirectAttributes, "删除成功");
		return "redirect:"+Global.getAdminPath()+"/sys/menu/?repage";
	}
	
	/**
	 * 导航菜单
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/nav", method = RequestMethod.GET)
	public void list(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		contextPath = request.getContextPath();
		
		List<Menu> menus = UserUtils.getMenuList();
			try {
			PrintWriter pw = response.getWriter();
			
			getNavigation(pw,menus,"1");
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
/*		try {
			PrintWriter pw = response.getWriter();
			
			String menu = 
			"<div class=\"list-group\">"
				+"<h1 title=\"抽奖活动\">"
					+"<img src=\"/springdraw/assets/admin/skins/default/nav/home.png\" />"
				+"</h1>"
				+"<div class=\"list-wrap\">"
					+"<h2>"
						+"抽奖活动<i></i>"
					+"</h2>"
					+"<ul>"
						+"<li><a navid=\"channel_main\" target=\"mainframe\"><span>抽奖设置</span></a>"
							+"<ul>"
								+"<li><a navid=\"channel_news\" target=\"mainframe\" href=\""+ contextPath +"/a/sd/award\"><span>奖品管理</span></a></li>"
								+"<li><a navid=\"channel_goods\" target=\"mainframe\"  href=\""+ contextPath +"/a/sd/section\"><span>抽奖设置</span></a></li>"
							+"</ul>"
						+ "</li>"
						+"<li><a navid=\"channel_main\" target=\"mainframe\"><span>中奖查询</span></a>"
							+"<ul>"
								+"<li><a navid=\"channel_news\" target=\"mainframe\"  href=\""+ contextPath +"/a/sd/member\"><span>用户列表</span></a></li>"
								+"<li><a navid=\"channel_goods\" target=\"mainframe\"  href=\""+ contextPath +"/a/sd/winner?isAward=1\"><span>中奖列表</span></a></li>"
							+"</ul>"
						+"</li>"
					+"</ul>" 
				+"</div>"
			+"</div>";
			pw.write(menu);
			
		} catch (IOException e) {
			e.printStackTrace();
		}*/
	}
	
	private void getNavigation(PrintWriter tw,List<Menu> menus,String parentId){
		
		List<Menu> subMenus = new ArrayList<Menu>();
		for(int i=0;i<menus.size();i++){
			Menu e = menus.get(i);
			if(e.getParent().getId().equals(parentId)){
				subMenus.add(e);
			}
		}
		
		if(menus==null || menus.size()==0) return;
		
		boolean isWrite = false;
		
		for(int i=0;i<subMenus.size();i++){
			Menu e = subMenus.get(i);
			
			if(e.getParent().getId().equals("1")){
				tw.write("<div class=\"list-group\">\n");
				tw.write("<h1 title=\"" + e.getName() + "\">");
				String icon = e.getIcon();
            	if(StringUtils.isEmpty(icon)){
            		icon = contextPath + "/assets/admin/skins/default/nav/home.png";
            	}else{
            		icon = contextPath + "/assets/admin/skins/default/nav/"+ icon +".png";
            	}
            	tw.write("<img src=\"" + icon + "\" />");
                tw.write("</h1>\n");
                tw.write("<div class=\"list-wrap\">\n");
                tw.write("<h2>" + e.getName() + "<i></i></h2>\n");
                //调用自身迭代
                getNavigation(tw,menus,e.getId());
                tw.write("</div>\n");
                tw.write("</div>\n");
			}else{
				if(e.getParent().getId().equals(parentId)){
					if(!isWrite){
						tw.write("<ul>\n");
						isWrite = true;
					}
					
					tw.write("<li>\n");
					tw.write("<a navid=\"" + e.getId() + "\"");
					if(!StringUtils.isEmpty(e.getHref())){
						tw.write(" href=\"" + contextPath +Global.getAdminPath() + e.getHref() + "\"");
					}
					
	                //tw.write(" icon=\"" + e.getIcon() + "\"");
					
					tw.write(" target=\"mainframe\">\n");
	                tw.write("<span>" + e.getName() + "</span>\n");
	                tw.write("</a>\n");
	                //调用自身迭代
	                getNavigation(tw,menus,e.getId());
	                tw.write("</li>\n");
	                if(i == subMenus.size()-1){
	                	 tw.write("</ul>\n");
					}
				}
			}
		}
	}
}
